package com.example.colorpickdemo;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.example.colorpickdemo.ui.activity.ColorPickTestActivity;
import com.example.colorpickdemo.ui.adapter.BluetoothItemAdapter;
import com.example.colorpickdemo.ui.adapter.listener.OnRecyclerViewItemClickListener;
import com.example.colorpickdemo.util.PermissionsManager;
import com.example.colorpickdemo.util.PhoneUtil;
import com.example.colorpickdemo.util.ToastUtil;
import com.example.colorpickdemo.widget.SpaceItemDecoration;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.mt.sdk.ble.MTBLEDevice;
import com.mt.sdk.ble.MTBLEManager;
import com.mt.sdk.ble.model.ErroCode;
import com.mt.sdk.help.BleConnectCallBack;
import com.mt.sdk.help.MTColorPickHelper;
import com.mt.sdk.help.bean.BluetoothMsg;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by daiguangtao on 2020/05/30.
 */
public class MainActivity extends AppCompatActivity implements XRecyclerView.LoadingListener, OnRecyclerViewItemClickListener,View.OnClickListener{


    private XRecyclerView mRecyclerView;

    private Button goCommandPageBtn;

    //蓝牙处理相关变量
    private MTColorPickHelper mMTColorPickHelper;
    private MTBLEManager manger;
    private Handler handle = new Handler();
    private boolean searchFlag = true;
    private PermissionsManager permissionsManager;
    private List<MTBLEDevice> mDeviceList = new ArrayList<MTBLEDevice>(); // 搜索到的所有设备

    private boolean isBleConnect = false;
    private int connBleId= 1;
    private String connBleMac = "";

    private Map<String,Integer> bleConnectMap = new HashMap<String,Integer>();

    // 蓝牙列表适配器
    private BluetoothItemAdapter mBluetoothItemAdapter;
    private List<BluetoothMsg> mBluetoothList;
    private BleConnectCallBack mBleConnectCallBack = new BleConnectCallBack(){

        @Override
        public void onSuccess() {

            if(!isBleConnect){
                Message tMessage = new Message();
                tMessage.what=1;
                tMessage.obj = "蓝牙连接成功";
                mHandler.handleMessage(tMessage);
            }
            isBleConnect = true;

            bleConnectMap.put(connBleMac,connBleId);
            connBleId++;
        }

        @Override
        public void onFail(ErroCode ErroCode) {
            if(ErroCode != null){
                Message tMessage = new Message();
                tMessage.what=1;
                tMessage.obj = "蓝牙连接失败:"+ErroCode.getCode()+":"+ErroCode.getMsg();
                mHandler.handleMessage(tMessage);
            }else{
                Message tMessage = new Message();
                tMessage.what=1;
                tMessage.obj = "蓝牙连接失败!";
                mHandler.handleMessage(tMessage);
            }

        }
    };


    private MTBLEManager.MTScanCallback scanCallback = new MTBLEManager.MTScanCallback() {

        @Override
        public void onScan(MTBLEDevice mtbleDevice) {
            if (mtbleDevice.getDevicetype() != MTBLEDevice.MTBLEDEVICETYPE.MTColorPickBLE) {
                return;
            }
            for (BluetoothMsg buletooth : mBluetoothList) {
                if (buletooth.getMacAdress().equals(mtbleDevice.getDevice().getAddress())) {
                    buletooth.setRssi(String.valueOf(mtbleDevice.getAvgRssi()));
                    return;
                }
            }
            mBluetoothList.add(new BluetoothMsg(mtbleDevice.getDevice().getName(), mtbleDevice.getDevice().getAddress(), String.valueOf(mtbleDevice.getAvgRssi())));
            mDeviceList.add(mtbleDevice);
            if (mBluetoothList.size() > 0) {
                mRecyclerView.refreshComplete();
            }
            mRecyclerView.refreshComplete();
            mBluetoothItemAdapter.notifyDataSetChanged();
        }

        @Override
        public void onScanFail(int i, String s) {
            ToastUtil.showtoast(getString(R.string.mainActivity_fail_find));
        }

        @Override
        public void onScanOver(ErroCode erroCode) {

        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mMTColorPickHelper = MTColorPickHelper.getinstance();
        permissionsManager = new PermissionsManager(this);
        boolean granted = permissionsManager.isPermissionGranted(PermissionsManager.ACCESS_FINE_LOCATION);
        if (!granted) {
            permissionsManager.requestPermission(PermissionsManager.ACCESS_FINE_LOCATION);
        }

        boolean granted1 = permissionsManager.isPermissionGranted(PermissionsManager.ACCESS_COARSE_LOCATION);
        if (!granted1) {
            permissionsManager.requestPermission(PermissionsManager.ACCESS_COARSE_LOCATION);
        }
        this.manger = mMTColorPickHelper.getBleManger();
        if (manger == null) {
            Toast.makeText(this, R.string.mainActivity_no_ble, Toast.LENGTH_SHORT).show();
            finish();
        }
        // 如果本地蓝牙没有开启，则开启
        if (!manger.isEnable()) {
            Intent mIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(mIntent, 1);
        }
        initView();
        initData();
        startScan();
    }

    private void initView(){
        mRecyclerView=this.findViewById(R.id.bluetooth_list);
        goCommandPageBtn=this.findViewById(R.id.goCommandPage);
    }
    private void initData(){
        isBleConnect = false;
        connBleId= 1;
        mBluetoothList = new ArrayList<BluetoothMsg>();
        mBluetoothItemAdapter = new BluetoothItemAdapter(this, mBluetoothList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.addItemDecoration(new SpaceItemDecoration(PhoneUtil.dipToPixel(5, this)));
        mRecyclerView.setLoadingListener(this);
        mRecyclerView.setLoadingMoreEnabled(false);
        mRecyclerView.setAdapter(mBluetoothItemAdapter);
        mRecyclerView.setPullRefreshEnabled(true);
        mBluetoothItemAdapter.setOnRecyclerViewItemClickListener(this);
        goCommandPageBtn.setOnClickListener(this);
        mMTColorPickHelper.setmBleConnectCallBack(mBleConnectCallBack);
    }

    public void startScan() {
        searchFlag = true;
        manger.stopScan();
        mBluetoothList.clear();
        handle.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (searchFlag) {
                    manger.startScan(MTBLEManager.ScanMode.FAST, null, scanCallback, 5, 1, 0);
                }
            }
        }, 1000);
    }

    @Override
    public void onRefresh() {
        startScan();
    }

    @Override
    public void onLoadMore() {

    }

    /**
     * startActivity
     *
     * @param clazz
     */
    protected void readyGo(Class<?> clazz) {
        Intent intent = new Intent(this, clazz);
        startActivity(intent);
    }
    @Override
    public void onItemClick(View view, int position) {
        if ((position > (mDeviceList.size() - 1)) || (position < 0)) {
            return;
        }
        final MTBLEDevice device = mDeviceList.get(position);
        if (device.getSetlev() > 1) {
            ToastUtil.showtoast(getString(R.string.mainActivity_notAllowConnect));
            return;
        }
        connBleMac=device.getDevice().getAddress();
        if(bleConnectMap.containsKey(connBleMac)){
            if(mMTColorPickHelper.getmBle(bleConnectMap.get(connBleMac))!=null&&mMTColorPickHelper.getmBle(bleConnectMap.get(connBleMac)).isConnected()){
                ToastUtil.showtoast("蓝牙已连接，请先断开");
                return;
            }
        }
        if(connBleId > 2){
            connBleId = 1;
        }

        if(mMTColorPickHelper.getmBle(connBleId) != null){
            mMTColorPickHelper.getmBle(connBleId).disConnect();
        }
        isBleConnect = false;
        mMTColorPickHelper.blueThoothConnect(device,getApplicationContext(),connBleId);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.goCommandPage:
                if(isBleConnect){
                    readyGo(ColorPickTestActivity.class);
                }else{
                    ToastUtil.showtoast("请先连接蓝牙");
                }
//                TcpHelper tTcpHelper = new TcpHelper();
//                tTcpHelper.login(new TcpHelper.TcpListener() {
//                    @Override
//                    public void onFail(String returnData) {
//                        Message tMessage = new Message();
//                        tMessage.what=1;
//                        tMessage.obj = returnData;
//                        mHandler.handleMessage(tMessage);
//                    }
//
//                    @Override
//                    public void onSuccess(String returnData) {
//                        Message tMessage = new Message();
//                        tMessage.what=1;
//                        tMessage.obj = returnData;
//                        mHandler.handleMessage(tMessage);
//                    }
//                });

                break;
        }

    }

    //在主线程里面处理消息并更新UI界面
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    final String rcvMsg = (String)msg.obj;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Looper.prepare();
                            Toast.makeText(MainActivity.this,rcvMsg,Toast.LENGTH_SHORT).show();
                            Looper.loop();
                        }
                    }).start();
                    break;
                default:
                    break;
            }

        }
    };
}
